package com.ye.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: TODO
 * @author: scott
 * @date: 2022年04月20日 20:07
 */
@Aspect
@Component
@Slf4j
public class ApiAddressAdvice {

    // 切点 GetMapping 注解
    @Pointcut("@annotation(com.ye.annotion.ApiAnnotation)")
    private void logAdvicePointcut() {
    }

    @Around("logAdvicePointcut()") //环绕执行（即环绕切点切入的方法，即切入的方法在下面方法内执行，其中 proceedingJoinPoint.proceed() 表示执行）
    @Order(0) // 执行顺序最高
    private Object returnLog(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        StringBuffer url = request.getRequestURL();
        String method = request.getMethod();
        Object object = pjp.proceed();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", object);
        long endTime = System.currentTimeMillis();
        jsonObject.put("api:    ", method.toUpperCase() + "   " + url);
        jsonObject.put("time", endTime - startTime + "ms");
        log.info(" 接口：" + url + " 请求方式：" + method + " 耗时：" + (endTime - startTime) + "ms");
        return jsonObject.toJSONString();
    }
}
